#ifndef CONNECTIONMANAGER_H
#define CONNECTIONMANAGER_H

#include <QMap>
#include <QObject>
#include <QTcpServer>
#include <QSignalMapper>

#include "packet/AbstractPacket.h"
#include "SocketData.h"
#include "PacketReaderWriter.h"

class ConnectionManager : public QObject
{
    Q_OBJECT
public:
    ConnectionManager();

    void init(QString address, int port);

    void sendPacket(AbstractPacket * packet);

public slots:
    void connectionOpened();
    void connectionClosed(int socketIndex);
    void readData(int socketIndex);

signals:
    void packetReceived(AbstractPacket *);
    void socketClosed(const QString & address, quint16 port);

private:
    void processPacketDataRead(unsigned char * data, quint32 length, int socketIndex);
    QTcpSocket * getClientSocket(QString address, quint16 port);

    QTcpServer *tcpServer;
    QMap<int, SocketData*> socketMap;
    QSignalMapper *mapperRead, *mapperClose;
    int socketIndexCounter;

    PacketReaderWriter packetReaderWriter;
};

#endif // CONNECTIONMANAGER_H
